package com.youbug.system.controller;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

public class Magic {

    public static void main(String[] args) {
        for (int j = 0; j < 100; j++) {

            List<String> props = Arrays.asList("杯子", "勺子", "筷子");

            Collections.shuffle(props);// 打乱顺序

            Map<String, Integer> magicPropsMap = new HashMap<>(props.size());

            for (int i = 0; i < props.size(); i++) {

                magicPropsMap.put(props.get(i), i);
            }
            // 第一步 筷子跟左边的东西互换,在最左边不用动
            int chopsticksIndex = magicPropsMap.get("筷子");

            if (chopsticksIndex != 0) {
                String left = findLeft(magicPropsMap, chopsticksIndex);

                magicPropsMap.put("筷子", chopsticksIndex - 1);

                magicPropsMap.put(left, magicPropsMap.get(left) + 1);
            }

            // 第二步 杯子跟右边的东西互换,在最右边不用动
            int cupIndex = magicPropsMap.get("杯子");

            if (cupIndex != 2) {
                String right = findRight(magicPropsMap, cupIndex);

                magicPropsMap.put("杯子", cupIndex + 1);

                magicPropsMap.put(right, magicPropsMap.get(right) - 1);
            }

            // 第三步 勺子跟左边的东西互换,在最左边不用动
            int spoonIndex = magicPropsMap.get("勺子");

            if (spoonIndex != 0) {
                String left = findLeft(magicPropsMap, spoonIndex);
                Integer integer = magicPropsMap.get(left);
                magicPropsMap.put("勺子", spoonIndex - 1);
                magicPropsMap.put(left,  integer + 1);
            }

            Set<String> strings = magicPropsMap.keySet();

            for (String key : strings) {
                if (magicPropsMap.get(key) == 2) {
                    System.out.println(key);
                }
            }
            // 类似冒泡排序，把最大的数字换到右边
        }
    }

    private static String findLeft(Map<String, Integer> magicPropsMap, int index) {

        AtomicReference<String> leftName = new AtomicReference<>();
        magicPropsMap.forEach((name,i)->{
            if(i == (index - 1)){
                leftName.set(name);
            }
        });
        String s = leftName.get();
        if(s==null){
            System.out.println(1);
        }
        return leftName.get();
    }
    private static String findRight(Map<String, Integer> magicPropsMap, int index) {

        AtomicReference<String> rightName = new AtomicReference<>();
        magicPropsMap.forEach((name,i)->{
            if(i == (index + 1)){
                rightName.set(name);
            }
        });
        return rightName.get();
    }

}
